package com.wuye.controller;

import com.wuye.model.Order;
import com.wuye.model.repair.Category;
import com.wuye.model.repair.RepairOrder;
import com.wuye.model.repair.RepairPerson;
import com.wuye.model.repair.RepairState;
import com.wuye.repository.CategoryRepository;
import com.wuye.repository.RepairOrderRepository;
import com.wuye.repository.RepairPersonRepository;
import com.wuye.web.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jiawenlong on 2016/7/26.
 */
@Controller
@RequestMapping("/admin/repair")
public class AdminRepairController extends BaseController {
    private Log log = LogFactory.getLog(this.getClass());
    @Autowired
    private SessionHandler sessionHandler;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    RepairPersonRepository repairPersonRepository;
    @Autowired
    RepairOrderRepository repairOrderRepository;

    /**
     * 管理报修分类
     */
    @RequestMapping("manageCategory.jspx")
    public String manageCategory(Model model) {
        return "redirect:/admin/repair/manageCategory.jspa";
    }

    /**
     * 编辑分类
     */
    @RequestMapping("editCategory.jspx")
    public ModelAndView editCategory(@RequestParam(value = "categoryId", defaultValue = "-1") long id) {
        Category category = categoryRepository.findById(id);
        ModelAndView md = new ModelAndView();
        md.setViewName("/admin/jspa/repair/editCategory");

        if (category != null) {
            md.addObject("category", category);
        }
        return md;
    }

    /**
     * 保存分类
     */
    @ResponseBody
    @RequestMapping(value = "saveCategory.jspx", method = RequestMethod.POST)
    public String saveCategory(@RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        Category category = new Category();
        if (object.has("id")) {
            category = categoryRepository.findById(object.getLong("id"));
            if (category == null) {
                category = new Category();
            }
        }
        if (object.has("parentId")) {
            category.setParentId(object.getInt("parentId"));
        }
        if (object.has("name")) {
            category.setName(object.getString("name"));
        }
        categoryRepository.save(category);
        return ST.ok.toJson();
    }

    /**
     * 删除菜单
     */
    @ResponseBody
    @RequestMapping("delCategory.jspx")
    public String delProductCategory(@RequestParam(value = "id", defaultValue = "-1") long id) {
        List<Category> childrenCategorys = categoryRepository.findByParentId(id);
        if (childrenCategorys.size() > 0) {
            return ST.dataHasChild.toJson();
        }
        Category category = categoryRepository.findById(id);
        if (category == null) {
            return ST.dataNotExists.toJson();
        }
        categoryRepository.delete(category);
        return ST.ok.toJson();
    }

    /**
     * 管理维修人员
     */
    @RequestMapping("manageRepairPersons.jspa")
    public String manageRepairPersons(HttpServletRequest request, Model model, @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "pageSize", defaultValue = "15") int pageSize
            , @RequestParam(value = "qField", defaultValue = "") String qField
            , @RequestParam(value = "qVal", defaultValue = "") String qVal
            , @RequestParam(value = "categoryId", defaultValue = "-1") long categoryId) {
        List<Object[]> persons = repairPersonRepository.queryUser(qField, qVal, pageSize * (page - 1), pageSize, categoryId);
        model.addAttribute("persons", persons);
        model.addAttribute("pagingString",
                Pagination.getPagingString(repairPersonRepository.queryUserCount(qField, qVal, categoryId), pageSize, page, request));
        return "/admin/jspa/repair/manageRepairPersons";
    }

    /**
     * 编辑维修人员
     */
    @RequestMapping("editRepairPerson.jspa")
    public String editRepairPerson(Model model, @RequestParam(value = "id", defaultValue = "-1") long id) {
        RepairPerson repairPerson = repairPersonRepository.findById(id);
        if (repairPerson != null) {
            model.addAttribute("repairPerson", repairPerson);
        }
        return "/admin/jspa/repair/editRepairPerson";
    }

    /**
     * 保存维修人员
     */
    @ResponseBody
    @RequestMapping(value = "saveRepairPerson.jspx", method = RequestMethod.POST)
    public String saveRepairPerson(@RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        RepairPerson person = new RepairPerson();
        if (object.has("id")) {
            person = repairPersonRepository.findById(object.getLong("id"));
            if (person == null) {
                person = new RepairPerson();
            }
        }
        if (object.has("categoryId")) {
            person.setCategoryId(object.getInt("categoryId"));
        }
        if (object.has("name")) {
            person.setName(object.getString("name"));
        }
        if (object.has("mobile")) {
            person.setMobile(object.getString("mobile"));
        }
        if (object.has("post")) {
            person.setPost(object.getString("post"));
        }
        repairPersonRepository.save(person);
        return ST.ok.toJson();
    }

    /**
     * 删除维修人员
     */
    @ResponseBody
    @RequestMapping("delRepairPerson.jspx")
    public String delRepairPerson(@RequestParam(value = "id", defaultValue = "-1") long id) {
        RepairPerson person = repairPersonRepository.findById(id);
        if (person == null) {
            return ST.dataNotExists.toJson();
        }
        repairPersonRepository.delete(person);
        return ST.ok.toJson();
    }

    /**
     * 管理报修订单
     */
    @RequestMapping("manageRepairOrder.jspa")
    public String manageRepairOrder(HttpServletRequest request, Model model
            , @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "pageSize", defaultValue = "15") int pageSize
            , @RequestParam(value = "qField", defaultValue = "") String qField
            , @RequestParam(value = "qVal", defaultValue = "") String qVal
            , @RequestParam(value = "orderState", defaultValue = "-1") int orderState
            , @RequestParam(value = "repairerId", defaultValue = "-1") long repairerId
            , @RequestParam(value = "dVal", defaultValue = "1970-01-01") String dVal
            , @RequestParam(value = "dVal2", defaultValue = "2090-12-12") String dVal2
    ) throws ParseException {
        dVal = dVal + " 00:00:00";
        dVal2 = dVal2 + " 23:59:59";
        RepairState[] states = RepairState.values();
        JSONObject object = new JSONObject();
        for (RepairState state : states) {
            object.put(state.state, state.getStateDesc());
        }
        List<Object[]> orders = repairOrderRepository.queryOrders(qField, qVal, pageSize * (page - 1), pageSize, orderState, repairerId, dVal, dVal2);
        model.addAttribute("orders", orders);
        model.addAttribute("pagingString",
                Pagination.getPagingString(repairOrderRepository.queryOrdersCount(qField, qVal, orderState, repairerId, dVal, dVal2), pageSize, page, request));
        model.addAttribute("states", object);
        return "/admin/jspa/repair/manageRepairOrder";
    }

    @RequestMapping("editRepairOrder.jspa")
    public String editRepairOrder(Model model, @RequestParam(value = "repairOrderId", defaultValue = "-1") long id) {
        RepairOrder repairOrder = repairOrderRepository.findById(id);
        if (repairOrder != null) {
            model.addAttribute("repairOrder", repairOrder);
        }
        return "/admin/jspa/repair/editRepairOrder";
    }

    /**
     * 保存报修单
     */
    @ResponseBody
    @RequestMapping(value = "saveRepairOrder.jspx", method = RequestMethod.POST)
    public String saveRepairOrder(HttpSession session, @RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        RepairOrder order = new RepairOrder();
        if (object.has("id")) {
            order = repairOrderRepository.findById(object.getLong("id"));
            if (order == null) {
                order = new RepairOrder();
                order.setState(0);
                order.setVisitState(0);
                if (object.has("admin")) {
                    order.setCreater("-1");
                } else {
                    UserSession userSession = sessionHandler.getUserSession(session);
                    order.setCreater(userSession.getUserId());
                }
            }
        }else{
            if (object.has("admin")) {
                order.setCreater("-1");
            } else {
                UserSession userSession = sessionHandler.getUserSession(session);
                order.setCreater(userSession.getUserId());
            }
        }
        if (object.has("connectionUserName")) {
            order.setConnectionUserName(object.getString("connectionUserName"));
        }
        if (object.has("connectionUserMobile")) {
            order.setConnectionUserMobile(object.getString("connectionUserMobile"));
        }
        if (object.has("connectionUserAddress")) {
            order.setConnectionUserAddress(object.getString("connectionUserAddress"));
        }
        if (object.has("categoryId")) {
            order.setCategoryId(object.getLong("categoryId"));
        }
        if (object.has("categorySecondId")) {
            order.setCategorySecondId(object.getLong("categorySecondId"));
        }
        if (object.has("repairPersonId")) {
            order.setRepairPersonId(object.getLong("repairPersonId"));
        }
        Date now = new Date();
        order.setAddTime(now);

        if (object.has("content")) {
            order.setContent(object.getString("content"));
        }
        if (object.has("remark")) {
            order.setRemark(object.getString("remark"));
        }

        repairOrderRepository.save(order);
        return ST.ok.toJson();
    }

    /**
     * 给报修单选择师傅
     */
    @ResponseBody
    @RequestMapping("choiceRepairPerson.jspa")
    public String choiceRepairPerson(Model model, @RequestParam("param") String param) {
        JSONObject object = JSONObject.fromObject(param);
        long id = object.getLong("repairOrderId");
        long personId = object.getLong("repairPersonId");
        RepairOrder repairOrder = repairOrderRepository.findOne(id);
        if (repairOrder != null) {
            RepairPerson person = repairPersonRepository.findById(personId);
            if (person == null) {
                log.info("=============没有找到对应师傅====================");
                return ST.dataNotExists.toJson();
            }
            repairOrder.setRepairPersonId(personId);
            repairOrderRepository.save(repairOrder);
            List<RepairPerson> ps = new ArrayList<>();
            ps.add(person);
            return ST.ok.getJsonObject(ps).toString();
        } else {
            return ST.dataNotExists.toJson();
        }
    }

    /**
     * 接单
     */
    @ResponseBody
    @RequestMapping("takingOrder.jspa")
    public String takingOrder(Model model, @RequestParam("id") long id) {
        return updateOrder(id, RepairState.confirmed);
    }

    /**
     * 取消订单
     */
    @ResponseBody
    @RequestMapping("cancelOrder.jspa")
    public String cancelOrder(Model model, @RequestParam("id") long id) {
        return updateOrder(id, RepairState.cancelled);
    }

    /**
     * 完成订单
     */
    @ResponseBody
    @RequestMapping("finishOrder.jspa")
    public String finishOrder(Model model, @RequestParam("id") long id) {
        return updateOrder(id, RepairState.financialConfirmation);
    }

    private String updateOrder(long id, RepairState state) {
        RepairOrder order = repairOrderRepository.findOne(id);
        if (RepairState.unconfirmed.equals(state)) {
            log.error("======================订单状态修改错误=====================");
            return ST.orderStateUpdateError.toJson();
        }
        if (null == order) {
            return ST.dataNotExists.toJson();
        } else {
            if (order.getState() < state.getState() && order.getState() < 2) {
                order.setState(state.getState());
                if (RepairState.financialConfirmation.equals(state)) {
                    order.setEndTime(new Date());
                }
                repairOrderRepository.save(order);
                org.json.JSONObject jo = ST.ok.getJsonObject();
                jo.put("orderState", order.getState());
                return jo.toString();
            } else {
                log.error("======================订单状态修改错误=====================");
                return ST.orderStateUpdateError.toJson();
            }
        }
    }

    /**
     * 导出汇总单
     *
     * @param request
     * @param resp
     * @param begin
     * @param end
     * @throws IOException
     */
    @RequestMapping("/repairOrderExport.jspa")
    public void repairOrderExport(HttpServletRequest request, HttpServletResponse resp,
                                  @RequestParam(value = "qField", defaultValue = "") String qField
            , @RequestParam(value = "qVal", defaultValue = "") String qVal
            , @RequestParam(value = "orderState", defaultValue = "-1") int orderState
            , @RequestParam(value = "repairerId", defaultValue = "-1") long repairerId
            , @RequestParam(value = "dVal", defaultValue = "1970-01-01") String begin
            , @RequestParam(value = "dVal2", defaultValue = "2090-12-12") String end) throws IOException {
        resp.setHeader("Content-Type", "application/octet-stream; charset=utf-8");
        OutputStream os = resp.getOutputStream();

        try {
            String name = "报修汇总表";
            log.info(name);
            int rowNum = 0;
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(name);
            begin = begin + " 00:00:00";
            end = end + " 23:59:59";

            List<Object[]> orders = repairOrderRepository.queryExportOrders(qField, qVal, orderState, repairerId, begin, end);
            if (orders.size() > 0) {
                HSSFFont font = wb.createFont();
                font.setBold(true);
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                HSSFCellStyle style = wb.createCellStyle();
                style.setFont(font);
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0, 1).setCellValue("国投物业一分公司报修订单");
                row = sheet.createRow(rowNum++);
                String[] names = {"序号", "订单编号", "报修内容", "订单状态", "联系方式", "报修时间", "维修分类", "维修师傅", "备注"};
                for (int i = 0; i < names.length; i++) {
                    row.createCell(i, 1).setCellValue(names[i]);
                }
                row.setRowStyle(style);
                int a = 1;

                for (Object[] objects : orders) {
                    HSSFRow itemRow = sheet.createRow(rowNum++);
                    itemRow.createCell(0, 1).setCellValue(a);
                    itemRow.createCell(1, 1).setCellValue(objects[0].toString());
                    itemRow.createCell(2, 1).setCellValue((null == objects[1] ? "" : objects[1].toString()) + "  "+ (null == objects[13] ? "" : objects[13].toString()) + "  " + (null == objects[2] ? "" : objects[2].toString()));
                    itemRow.createCell(3, 1).setCellValue(RepairState.find(Integer.parseInt(objects[3].toString())).getStateDesc());
                    itemRow.createCell(4, 1).setCellValue((null==objects[4]?"":objects[4].toString() )+ " " + (null==objects[5]?"":objects[5].toString())+ "  "  + "\n" + (null==objects[6]?"":objects[6].toString()));
                    itemRow.createCell(5, 1).setCellValue((null == objects[7] ? "" : objects[7].toString().substring(0, 19)));
                    itemRow.createCell(6, 1).setCellValue((null == objects[8] ? "" : objects[8].toString()) + "");
                    itemRow.createCell(7, 1).setCellValue(Integer.parseInt(objects[9] + "") == 0 ? "--" : (null == objects[10] ? "" : objects[10].toString()) + "   " + "\n" + (null == objects[11] ? "" : objects[11].toString()));
                    itemRow.createCell(8, 1).setCellValue(null == objects[12] ? "" : objects[12].toString());
                    a++;
                }
            }
            resp.addHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes(), "iso-8859-1") + ".xls");
            wb.write(os);
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.addHeader("Content-Disposition", "attachment; filename*=UTF-8''error.txt");
            os.write("出错了，请重试".getBytes());
            os.write(e.getMessage().getBytes());
        }
        os.flush();
        os.close();
    }


    /**
     * 客户回访
     */
    @RequestMapping("manageFeedback.jspa")
    public String feedback(HttpServletRequest request, Model model
            , @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "pageSize", defaultValue = "15") int pageSize
            , @RequestParam(value = "qField", defaultValue = "") String qField
            , @RequestParam(value = "qVal", defaultValue = "") String qVal
            , @RequestParam(value = "repairerId", defaultValue = "-1") long repairerId
            , @RequestParam(value = "dVal", defaultValue = "1970-01-01") String dVal
            , @RequestParam(value = "dVal2", defaultValue = "2090-12-12") String dVal2
    ) throws ParseException {
        int orderState = 3;

        List<Object[]> visitOrders = repairOrderRepository.queryFeedbackOrders(qField, qVal, pageSize * (page - 1), pageSize, orderState, repairerId, dVal, dVal2, 1);
        List<Object[]> unVisitOrders = repairOrderRepository.queryFeedbackOrders(qField, qVal, pageSize * (page - 1), pageSize, orderState, repairerId, dVal, dVal2, 0);
        model.addAttribute("visitOrders", visitOrders);
        model.addAttribute("unVisitOrders", unVisitOrders);
        model.addAttribute("pagingStringVisit",
                Pagination.getPagingString(repairOrderRepository.queryFeedbackOrdersCount(qField, qVal, orderState, repairerId, dVal, dVal2, 1), pageSize, page, request));
        model.addAttribute("pagingStringUnVisit",
                Pagination.getPagingString(repairOrderRepository.queryFeedbackOrdersCount(qField, qVal, orderState, repairerId, dVal, dVal2, 0), pageSize, page, request));
        return "/admin/jspa/repair/manageFeedback";
    }

    /**
     * 更新回访状态和客户反馈
     * @param model
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("updateFeedback.jspa")
    public String updateFeedback(Model model, @RequestParam("id") long id, @RequestParam("feedback") String feedback, @RequestParam("visitState") int visitState) {
        RepairOrder order = repairOrderRepository.findOne(id);
        if(null == order){
            return ST.dataNotExists.toJson();
        }else{
            order.setVisitState(visitState);
            order.setFeednack(feedback);
            repairOrderRepository.save(order);
            return ST.ok.toJson();
        }
    }
}
